﻿using Nancy;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Web;

namespace API_Service.Common
{
    public class FileControlService:BaseLogicService
    {
        private string _srvFilePath = "";
        public FileControlService()
        {
            _srvFilePath = ConfigurationManager.AppSettings["upload_filepath"];
            if (string.IsNullOrEmpty(_srvFilePath))
            {
                _srvFilePath = HttpContext.Current.Server.MapPath("~");
            }
        }
        public Dictionary<string, string> UploadFile(dynamic vFiles, dynamic vFileType, dynamic vServerPath = null)
        {
            Dictionary<string,string> lstFilePath = new Dictionary<string, string>();

            string _filePath = "/content/upload/" + vFileType + "/";
            try
            {
                //file path
                string fileSavePath = this._srvFilePath + "/" + _filePath + "/";
                if (!System.IO.Directory.Exists(fileSavePath))
                {
                    System.IO.Directory.CreateDirectory(fileSavePath);
                }

                foreach (HttpFile tmpFile in vFiles)
                {
                    //write file
                    var file = new System.IO.FileInfo(fileSavePath + "/" + tmpFile.Name);
                    if (!file.Exists)
                    {
                        using (System.IO.FileStream flStream = new System.IO.FileStream(fileSavePath + "/" + file.Name, System.IO.FileMode.Create))
                        {
                            tmpFile.Value.CopyTo(flStream);
                        };
                    }

                    lstFilePath.Add(tmpFile.Key, vServerPath + _filePath + file.Name);

                    Logger.WriteDebug("upload file success. file name:" + file.Name);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteError(MethodBase.GetCurrentMethod().Name, ex);
                throw ex;                
            }

            return lstFilePath;
        }

        public ExecutionResult<dynamic> DeleteFile(string vFile, string vServerPath)
        {
            ExecutionResult<dynamic> result;
            result = new ExecutionResult<dynamic>();            
            try
            {
                var localFiles = _srvFilePath + vFile.Substring(vServerPath.Length);
                if (File.Exists(vFile))
                {
                    File.Delete(localFiles);
                }
                result.Status = true;
                result.Message = "Delete file success.";
            }
            catch (Exception ex)
            {
                result.Status = false;
                result.Message = "Delete server file fail. Exception msg:" + ex.Message;
                Logger.WriteError(MethodBase.GetCurrentMethod().Name, ex);
            }

            return result;
        }
    }
}